package org.springblade.auth.social.wechatEnterprise.endpoint;

import lombok.AllArgsConstructor;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springblade.auth.social.wechatEnterprise.utils.WechatEnterpriseUtil;
import org.springblade.core.tenant.annotation.NonDS;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.system.feign.ISysClient;
import org.springblade.system.user.entity.User;
import org.springblade.system.user.entity.UserInfo;
import org.springblade.system.user.entity.UserOauth;
import org.springblade.system.user.feign.IUserClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.rmi.ServerException;
import java.util.Map;
import java.util.Objects;

@NonDS
@RestController
@RequestMapping
@AllArgsConstructor
public class WechatEnterpriseEndpoint {

	private final ISysClient sysClient;
	private final IUserClient userClient;

	/**
	 * 绑定企业微信OauthUser
	 */
	@RequestMapping("/oauth/render/wechat/binding-wechatenterprise")
	public R bindingOauthUser(@RequestParam Map<String, String> parameters, HttpServletResponse response) throws ServerException {
		String tenantId = parameters.get("tenantId");
		// 开放平台授权码
		String code = parameters.get("code");
		// 开放平台状态吗
		String state = parameters.get("state");
		String userid = parameters.get("userId");
		if (StringUtil.isEmpty(userid)) {
			throw new ServerException("userId无效");
		}
		AuthRequest authRequest = WechatEnterpriseUtil.getAuthRequest(tenantId, sysClient);
		AuthCallback authCallback = new AuthCallback();
		authCallback.setCode(code);
		authCallback.setState(state);
		AuthResponse authResponse = authRequest.login(authCallback);
		if (authResponse.getCode() == 2000) {
			AuthUser authUser = (AuthUser) authResponse.getData();
			// 组装数据
			UserOauth userOauth = Objects.requireNonNull(BeanUtil.copy(authUser, UserOauth.class));
			userOauth.setSource(authUser.getSource());
			userOauth.setTenantId(tenantId);
			userOauth.setUuid(authUser.getUuid());
			// 远程调用，获取认证信息
			R<UserInfo> result = userClient.userAuthInfo(userOauth);
			if (result.isSuccess()) {
				User user = result.getData().getUser();
				if (user == null || user.getId() == null || user.getId() == -1) {
					UserOauth oauth = new UserOauth();
					oauth.setUserId(Long.valueOf(userid));
					oauth.setId(Long.valueOf(result.getData().getOauthId()));
					Boolean data = userClient.bingdingWechatEnterpriseOauth(oauth).getData();
					if (!data) {
						return R.fail("绑定失败");
					}
					return R.status(data);
				} else {
					return R.success("无需重复绑定");
				}
			} else {
				throw new ServerException("social grant failure, feign client return error");
			}
		} else {
			throw new ServerException("social grant failure, auth response is not success");
		}
	}

	/**
	 * 企业微信授权完毕跳转
	 */
	@RequestMapping("/oauth/render/wechatenterprise/{tenantId}")
	public void renderWechatEnterpriseAuth(@PathVariable("tenantId") String tenantId, HttpServletResponse response) throws IOException {
		AuthRequest authRequest = WechatEnterpriseUtil.getAuthRequest(tenantId, sysClient);
		String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
		response.sendRedirect(authorizeUrl);
	}

	/**
	 * 企业微信绑定跳转
	 */
	@RequestMapping("/oauth/render/wechatenterprisebinding")
	public void renderWechatEnterpriseBinding(@RequestParam Map<String, String> parameters, HttpServletResponse response) throws IOException {
		String tenantId = parameters.get("tenantId");
		String userId = parameters.get("userId");
		AuthRequest authRequest = WechatEnterpriseUtil.getBindingAuthRequest(tenantId, userId, sysClient);
		String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
		response.sendRedirect(authorizeUrl);
	}
}
